package com.woniu.woniu_bx.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {
    @Autowired
    private JWtProperties jWtProperties;

    public String createJWT(int id,String account){
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.MINUTE, jWtProperties.getExpireSeconds());
        Map<String,Object> payload = new HashMap<String,Object>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        //载荷
        payload.put("id", id);
        payload.put("account", account);

        String key = jWtProperties.getSecret();
        String token = JWTUtil.createToken(payload, key.getBytes());

        return token;
    }
    public boolean verifyJWT(String token){
        String key = jWtProperties.getSecret();
        boolean verifyKey = false;
        try{
            JWT jwt = JWTUtil.parseToken(token);
            verifyKey = jwt.setKey(key.getBytes()).verify();
            return verifyKey;
        }catch (Exception e){
            e.printStackTrace();
        }
        return verifyKey;
    }
    public int getID(String token){
        JWT jwt = JWTUtil.parseToken(token);
        return (int)jwt.getPayload("id");
    }
}